﻿using SUNRPA.CONTROLS.IMPL.domain;
using RPAVIEW.util;
using RPAVIEW.views.EditPage.flows;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using SUNRPA.CONTROLS.IMPL.domain.constant;
using SUNRPA.CONTROLS.IMPL.util;
using Newtonsoft.Json;
using System.Collections.Concurrent;
using SUNRPA.CONTROLS.IMPL.domain.flowRunningVar;

namespace RPAVIEW.views.EditPage {
    /// <summary>
    /// EditHome.xaml 的交互逻辑
    /// </summary>
    public partial class EditHome : UserControl {
        public static LogUtil logger = new LogUtil(typeof(EditHome));
        public delegate void GoBackDelgage();
        public event GoBackDelgage GoBackEvent;
        public TaskRunner runner;
        
        public EditHome(TaskRunner tr) {
            InitializeComponent();
            runner = tr;
            this.DataContext = tr.runnerContextVarData;
            this.pnReadOnly.AddHandler(ListViewItem.MouseLeftButtonDownEvent, new MouseButtonEventHandler(this.TurnToEdit), true);
        }

        private void goBack(object sender, RoutedEventArgs e) {
            MessageBoxResult re = MessageBox.Show("确定退出么？", "提示", MessageBoxButton.OKCancel);
            if(MessageBoxResult.OK.Equals(re)) { 
                GoBackEvent();
            }
        }

        //控件放下
        public void ControlDrop(object sender, DragEventArgs e) {
            MainWindow mainWindow = WindowUtil.GetWindow<MainWindow>();
            TreeViewItem targetControl = (TreeViewItem)e.Data.GetData(typeof(TreeViewItem));
            //置灰
            mainWindow.Opacity = 0.5;
            try{ 
                FlowEditWindow flowEditWindow = new FlowEditWindow(targetControl, this);
                flowEditWindow.Owner = mainWindow;
                flowEditWindow.ShowDialog();
            } finally { 
                mainWindow.Opacity = 1;
                e.Handled = true;
            }
        }

        /// <summary>
        /// 运行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void RunTask(object sender, ExecutedRoutedEventArgs e) {
            ProcessInfo processInfo = (ProcessInfo)this.FindResource("processInfo");
            if(this.FlowItems.Children.Count > 0) {
                List<string> flowItemInfos = new List<string>();
                List<FlowItem> flowItems = new List<FlowItem>();
                for(int i = 0; i < this.FlowItems.Children.Count; i++) {
                    FlowItemView itemView = this.FlowItems.Children[i] as FlowItemView;
                    FlowItem item = itemView.DataContext as FlowItem;
                    flowItems.Add(item);
                    flowItemInfos.Add(itemView.info.Text);
                }
                logger.Info("开始运行流程:{ProcessName}，编辑器直接运行", processInfo.processName);
                runner.RunTask(flowItems, flowItemInfos);
            }
        }
        #region command define
        private void CanSaveFlow(object sender, CanExecuteRoutedEventArgs e){
			e.CanExecute = true;
		}
        private void CanRunTask(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = true;
		}

        
        private void DebugTask(object sender, ExecutedRoutedEventArgs e) {
        }

        private void CanDebugTask(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = true;
		} 
        private void Record(object sender, ExecutedRoutedEventArgs e) {
        }

        private void CanRecord(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = true;
		} 
        private void DataCapture(object sender, ExecutedRoutedEventArgs e) {
        }

        private void CanDataCapture(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = true;
		} 
        private void EleCapture(object sender, ExecutedRoutedEventArgs e) {
        }

        private void CanEleCapture(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = true;
		}
        #endregion
        private void SaveFlow(object sender, ExecutedRoutedEventArgs e) {
            //保存，若为新增流程没有AccountId，先新增流程信息后上传流程文件，若上传文件失败则删掉之前新增的流程信息
            #region 保存流程信息
            HttpUtil httpUtil = HttpUtil.getInstance(SystemUtil.GetAPPConfig("ControlBaseIp") + SystemUtil.GetAPPConfig("ProcessUri"));
            ProcessInfo processInfo = (ProcessInfo)this.FindResource("processInfo");
            UserInfo userInfo = (System.Windows.Application.Current as App).currentUser;
            HttpResponse<ProcessInfo> res = null;
            if(string.IsNullOrEmpty(processInfo.processId)) { 
                processInfo.accountId = userInfo.accountId;
                res = httpUtil.SendPost<ProcessInfo>("/add", processInfo);
            } else { 
                res = httpUtil.SendPost<ProcessInfo>("/edit", processInfo);
            }
            if(res.Code == 500) { 
                MessageBox.Show($"保存失败:{res.Msg}");
                return;
            } else { 
                processInfo = res.Data;
                this.Resources.Remove("processInfo");
                this.Resources.Add("processInfo", processInfo);
            }
            #endregion

            #region 保存上传流程实体
            //全局参数
            ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>> globleData = this.DataContext as ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>>;
            //流程项
            int count = this.FlowItems.Children.Count;
            List<FlowItem> flowItems = new List<FlowItem>();
            for(int i = 0; i < count; i++) {
                FlowItemView itemView = this.FlowItems.Children[i] as FlowItemView;
                FlowItem item = itemView.DataContext as FlowItem;
                flowItems.Add(item);
            }
            JsonSerializerSettings set  = new JsonSerializerSettings();
            set.TypeNameHandling = TypeNameHandling.Auto;
            string globleDataJson = JsonConvert.SerializeObject(globleData, Formatting.Indented, set);
            string flowItemsJson = JsonConvert.SerializeObject(flowItems, Formatting.Indented, set);
            Dictionary<string, string> saveFlows = new Dictionary<string, string>();
            Dictionary<string, string> exterParam = new Dictionary<string, string>();
            exterParam.Add("processId", processInfo.processId);
            saveFlows.Add(DefaultContents.SERIALIZE_GOLBLE_DATA, globleDataJson);
            saveFlows.Add(DefaultContents.SERIALIZE_FLOWITEMS, flowItemsJson);
            byte[] flowBytes = FileUtil.CreateZipFromMemory(saveFlows);
            HttpResponse<object> upLoadRes = httpUtil.UploadFile<object>("/upload", processInfo.processName + ".zip", fileBytes:flowBytes,exterParam:exterParam);
            if(upLoadRes.Code == 500) { 
                MessageBox.Show($"保存失败:{upLoadRes.Msg}");
                return;
            } else { 
                MessageBox.Show("保存成功");
            }
            #endregion
        }

        private void TurnToEdit(object sender, MouseButtonEventArgs e) {
            this.pnReadOnly.Visibility = Visibility.Collapsed;
            this.pnEdit.Visibility = Visibility.Visible;
        }

        private void TurnToReadOnly(object sender, KeyboardFocusChangedEventArgs e) {
            this.editName.GetBindingExpression(TextBox.TextProperty).UpdateSource();
            this.pnReadOnly.Visibility = Visibility.Visible;
            this.pnEdit.Visibility = Visibility.Collapsed;
        }
    }
}
